<?php

/**
 * 资讯类
 */
class newsModel
{


    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    /**
     * 创建一条资讯
     * @return array
     */
    public function createNews($newsData)
    {
        $news_id = $this->db->insertRowTable('r_news', $newsData);
        if($news_id)
        {
            $newsData['news_id'] = $news_id;
            if(isset($newsData['is_show']) && $newsData['is_show'] == 1)
            {
                if(empty($newsData['a_channel']))
                {
                    $this->redis->zadd(REDIS_PREFIX . 'NewsList', $newsData['is_top'] == 1 ? $newsData['add_time']*10 : $newsData['add_time'], $news_id);
                }
                else
                {
                    $newsData['a_end_time'] > time() && $this->redis->HSET(REDIS_PREFIX.'ActivityNews', $newsData['a_channel'], $news_id);
                }
            }
            $this->redis->hmset(REDIS_PREFIX . 'NewsInfo_' . $news_id, $newsData);
            return $news_id;
        }
        else
        {
            return false;
        }
    }

    /**
     * 编辑资讯
     * @return array
     */
    public function updateNews($newsData)
    {
        if(!isset($newsData['news_id'])) return false;
        if($this->db->updateRowTable('r_news', $newsData))
        {
            $news_id = $newsData['news_id'];
            if(isset($newsData['is_show']) && $newsData['is_show'] == 0)
            {
                $this->redis->zrem(REDIS_PREFIX . 'NewsList', $news_id);
            }
            else
            {
                if(isset($newsData['a_channel']) && !empty($newsData['a_channel']))
                {
                    $this->redis->zrem(REDIS_PREFIX . 'NewsList', $news_id);
                    $newsData['a_end_time'] > time() && $this->redis->HSET(REDIS_PREFIX.'ActivityNews', $newsData['a_channel'], $news_id);
                }
                elseif(isset($newsData['is_top']) && isset($newsData['add_time']))
                {
                    $this->redis->zadd(REDIS_PREFIX . 'NewsList', $newsData['is_top'] == 1 ? $newsData['add_time']*10 : $newsData['add_time'], $news_id);
                }
            }
            $this->redis->hmset(REDIS_PREFIX . 'NewsInfo_' . $news_id, $newsData);
            return true;
        }
        else
        {
            return false;
        }
    }
    
    /*
     *获取资讯原始内容
     */
    public function getRawNewsInfo($news_id){
        $result = false;
        if($news_id)
        {
            $result = $this->redis->hgetall(REDIS_PREFIX. 'NewsInfo_' . $news_id);
            if(!$result)
            {
                $result = $this->db->getRowTable('r_news', array(), "news_id = '{$news_id}'");
                if($result)
                {
                    $this->redis->hmset(REDIS_PREFIX . 'NewsInfo_' . $news_id, $result);
                }
            }
        }
        return $result;
    }
    
    /*
     * 通过评论id获得资讯
     */
    public function getNewsByComment($comment_id){
        $news_id = $this->db->getOne("select news_id from r_news_comment where comment_id= {$comment_id}");
        return $this->getRawNewsInfo($news_id);
    }
    
    /**
     * 获取资讯内容
     * @int $news_id
     * @return array
     */
    public function getNewsInfo($news_id)
    {
        $result = false;
        if($news_id)
        {
            $result = $this->redis->hgetall(REDIS_PREFIX. 'NewsInfo_' . $news_id);
            if(!$result)
            {
                    $result = $this->db->getRowTable('r_news', array(), "news_id = '{$news_id}'");
                if($result)
                {
                    $this->redis->hmset(REDIS_PREFIX . 'NewsInfo_' . $news_id, $result);
                }
            }
            if(!empty($result) && isset($result['content']))
            {
                $result['content'] = str_replace('joggers://topic/image/', '', $result['content']);
            }
            if(!empty($result))
            {
				if(isset($result['tag']) && common::is_json($result['tag']))
				{
					$result['tag'] = isset($result['otag']) ? $result['otag'] : '';
				}
				if(isset($result['imgCount']))
				{
                    $result['thumb_img'] = json_decode($result['thumb_img'], true);
					$thumb_img = array();
					if($result['imgCount'] == 2){
						$result['imgCount'] = 1;
						foreach($result['thumb_img'] as $key=> $v)
						{
							if(count($thumb_img) < 1)
							{
								$thumb_img[] = $v;
							}
						}
					}
					elseif($result['imgCount'] >= 3){
						$result['imgCount'] = 3;
                        if(!empty($result['thumb_img'])){
                            foreach($result['thumb_img'] as $key=> $v)
                            {
                                if(count($thumb_img) < 3)
                                {
                                    $thumb_img[] = $v;
                                }
                            }
                        }
					}
					$result['thumb_img']= $thumb_img;
					$result['imgCount']= count($thumb_img);
				}
				else{
					$result['imgCount'] = 0;
				}
                if(!isset($result['author']) || $result['author'] == '')
                {
                    $result['author'] = isset($result['uid']) ? $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$result['uid'], 'nickname') : '佚名';
                }
				if(isset($result['board'])) {unset($result['board']);}
				//if(isset($result['uid'])) {unset($result['uid']);}
				if(isset($result['sourceImg'])) {unset($result['sourceImg']);}
            }
        }
        return $result;
    }

    /**
    * 获取资讯列表
    * @point 起始点
    * @direc 数据加载方式
    * @p  页码
    * @offset 每页数据条数
    * @return array
    */
    public function getNewsList($point = 0, $direc = 'next', $offset = 10, $p =0)
    {
        $data = array();
        $offset = empty($offset) ? 10 : $offset;
        if($p)
        {
            $num = $this->db->getOne("select count(*) from r_news where board like '%\"0\"%'");
            //分页
            require FILE . 'lib/page.class.php';
            $page = new Page($num, $offset);
            $pageStr = $page->show();
            $this->base->view->assign('pageStr', $pageStr);

            $start = ($p - 1) * $offset;
            $sql = "select news_id, title,short_desc,tag,author,add_time,lastupdate,is_show,total_comment,imgCount, is_top, a_channel from r_news where board like '%\"0\"%' order by add_time DESC limit $start,$offset";
            $data = $this->db->getAll($sql);
            if($data)
            {
                $pushData = $this->redis->SMEMBERS(REDIS_PREFIX . 'pushWorkRecord');
                $clickCount = array();
                foreach ($pushData as $key => $value) {
                    $clickData = json_decode($value, true);
                    if($clickData['push_type'] == 'newsinfo')
                    {
                        $clickCount[$clickData['push_value']] = isset($clickCount[$clickData['push_value']]) ? $clickCount[$clickData['push_value']]+1 : 1;
                    }
                }
                $publishChannel = common::$publishChannel;
                foreach ($data as $key => & $value) {
                    $value['channel_name'] = $value['a_channel'] ? $publishChannel[$value['a_channel']] : 'N/A';
                    $value['clickCount'] = isset($clickCount[$value['news_id']]) ? $clickCount[$value['news_id']] : 0;
                }
            }
        }
        else
        {
            $point = intval($point);
            $packageChannel = common::request('packageChannel', 'G','');
            $this->redis->ZREM(REDIS_PREFIX . 'NewsList', "");
            $pointTime = $this->redis->ZSCORE(REDIS_PREFIX . 'NewsList', $point);

            $limit = array(0, intval($offset));
            if(empty($point) && !empty($packageChannel))
            {
                $add_news_id = $this->redis->hget(REDIS_PREFIX.'ActivityNews', $packageChannel);
                $add_news_info = $this->getNewsInfo($add_news_id);
                if($add_news_info && $add_news_info['a_start_time'] <= time() && $add_news_info['a_end_time'] > time() && $add_news_info['is_show'] == 1)
                {
                    $sql = "select count(comment_id) from r_news_comment where news_id = '{$add_news_id}'";
                    $lightLimt = $this->base->config['NEWS_HOT_COMMENT_LIMIT'];
                    $sql .= " and lights >= '{$lightLimt}'";
                    $add_news_info['total_lights'] = $this->db->getOne($sql);
                    unset($add_news_info['content'], $add_news_info['lastupdate'], $add_news_info['is_show'],$add_news_info['is_top'], $add_news_info['a_channel'], $add_news_info['a_start_time'], $add_news_info['a_end_time']);
                    $data[] = $add_news_info;
                }
            }
            if($direc == 'next')
            {
                $newsIds = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX .'NewsList', empty($pointTime) ? '+inf' : '('.$pointTime, '-inf', array('limit' => $limit));
            }
            else
            {
                $newsIds = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX . 'NewsList', '+inf','-inf', array('limit' => $limit));
            }
            if($newsIds)
            {
                foreach ($newsIds as $key => $news_id)
                {
                    $newsInfo = $this->getNewsInfo($news_id);
                    if(!empty($newsInfo))
                    {
                        unset($newsInfo['content'], $newsInfo['lastupdate'], $newsInfo['is_show'],$newsInfo['is_top'], $newsInfo['a_channel'], $newsInfo['a_start_time'], $newsInfo['a_end_time']);
                        $sql = "select count(comment_id) from r_news_comment where news_id = '{$news_id}'";
                        $lightLimt = $this->base->config['NEWS_HOT_COMMENT_LIMIT'];
                        $sql .= " and lights >= {$lightLimt}";
                        $newsInfo['total_lights'] = $this->db->getOne($sql);
                        $data[] = $newsInfo;
                    }
                }
            }
        }
        return $data;
    }
    /**
     * 获取某条资讯评论列表
     * @int news_id 资讯id
     * @string type 评论类型 all hot
     * @int point  界限点：一个评论ID
     * @int direc  数据加载方式  next prev
     * @int offset  要获取的评论数量
     * @int p  页码
     * 说明：客户端使用前5个参数
     * @return array()
     */
    public function getNewsCommentList($news_id, $type = 'all', $point = 0, $direc = 'next',$offset = 10,$p = 0)
    {
        $result = array();
        empty($direc) && $direc = 'next';
        if($news_id)
        {
            empty($offset) && $offset = 10;
            $sql = "select * from r_news_comment where news_id = {$news_id} ";
            $count_sql = "select count(comment_id) from r_news_comment where news_id = {$news_id} ";
            if($type == 'hot')
            {
                $offset = 10;
                $lightLimt = $this->base->config['NEWS_HOT_COMMENT_LIMIT'];
                $sql .= " and lights >= {$lightLimt} ";
                $count_sql .= " and lights >= {$lightLimt}";
            }
            if($p >0)
            {
                //分页
                require FILE . 'lib/page.class.php';
                $num = $this->base->db->getone($count_sql);
                $offset = empty($offset) ? 10 : $offset;
                $page = new Page($num, $offset);
                $pageStr = $page->show();
                $this->base->view->assign('pageStr', $pageStr);

                $start = ($p-1) * $offset;
                $sql .= $type == 'hot' ? ' order by lights DESC' : ' order by comment_id DESC';
                $sql .= " limit {$start}, {$offset}";
            }
            else
            {
                $sql .= ' and is_show = 1';
                // if(!empty($point))
                // {
                //     $sql .= " and comment_id != {$point}";
                //     $point = $this->db->getOne("select add_time from r_news_comment where news_id = {$news_id}  and comment_id = {$point}");
                // }
                if($point > 0 && $type != 'hot')
                {
                    $sql .= " and comment_id ";
                    $sql .= $direc == 'prev' ? "> {$point} " : "< {$point}";
                }
                elseif($type == 'hot')
                {
                    $sql .= ' order by lights DESC';
                }
                $type != 'hot' && $sql .=" order by comment_id DESC limit {$offset}";
            }
            $result = $this->db->getall($sql);
        }
        if($result)
        {
            foreach ($result as $k => & $comment) {
                $comment['comment_content'] = $this->replaceComment($comment['comment_content']);
                $comment['floor'] = $this->redis->zrank(REDIS_PREFIX.'NewsComFloor_'.$news_id, $comment['comment_id'])+1;
                $comment['nickname'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $comment['uid'], 'nickname');
                $comment['header'] = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $comment['uid'], 'header');
            }
        }
        return $result;
    }
    /**
     * 更新某资讯的热门评论
     * @int news_id 资讯id
     * @return
     */
    public function updateHotComments($news_id)
    {
        $result = false;
        $hotCommentList = $this->getNewsCommentList($news_id, 'hot');
        $result = $this->redis->set(REDIS_PREFIX .'hotCommentList'.$news_id, json_encode($hotCommentList));
        return $result;
    }
    /**
     * 获取某资讯的热门评论
     * @int news_id 资讯id
     * @return
     */
    public function getHotComments($news_id)
    {
        $result = $this->redis->get(REDIS_PREFIX .'hotCommentList'.$news_id);
        if(empty($result))
        {
            $this->updateHotComments($news_id);
        }
        $result = json_decode($this->redis->get(REDIS_PREFIX .'hotCommentList'.$news_id), true);
        if(!empty($result))
        {
            foreach ($result as & $v) {
                !isset($v['father_id']) && $v['father_id'] = "0";
                !isset($v['father_nickname']) && $v['father_nickname'] = "";
            }
        }
        return $result;
    }
    /**
     * 点亮某条资讯评论
     * @int comment_id 评论id
     * @return int  is_success 是否成功
     */
    public function lightenNewsComment($comment_id = 0)
    {
        $comInfo = $this->db->getRow("select comment_id, news_id, uid, lights from r_news_comment where comment_id = {$comment_id} and is_show =1");
        if(!empty($comInfo))
        {
            //检查用户是否已点亮过该评论
            if($this->redis->hexists(REDIS_PREFIX.'NewsCommentLight'.$comment_id, $this->base->uid))
            {
                $_ENV['error']->getErrors(405);
                exit();
            }
            $is_success = $this->db->query("update r_news_comment set lights = lights +1 where comment_id = {$comment_id}") ? 1 : 0;
            if($is_success)
            {
                $this->redis->hset(REDIS_PREFIX.'NewsCommentLight'.$comment_id, $this->base->uid, time());
                $comInfo['lights'] +1 >= $this->base->config['NEWS_HOT_COMMENT_LIMIT'] && $this->updateHotComments($comInfo['news_id']);
            }
            return $is_success;
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }
    /**
     * 发布评论
     * @param news_id 资讯id
     * @param comment_content 评论内容
     * @param father_id 父级评论id
     * @return int  comment_id  生成的评论id
     */
    public function publishNewsComment($news_id, $comment_content, $uid, $father_id = 0, $comment_img = '')
    {
        $postInfo = $this->base->load('bbs')->getPostInfo($news_id);
        if($postInfo && $postInfo['is_show'] == 1 && $uid)
        {
            if(!empty($father_id))
            {
                $father_uid = $this->db->getone("select uid from r_news_comment where news_id = {$news_id} and comment_id = {$father_id} limit 1");
                if(empty($father_uid))
                {
                    $_ENV['error']->getErrors(101);
                    exit();
                }
            }
            $img_size = empty($comment_img) ? array() : getimagesize($_FILES['comment_img']['tmp_name']);
            if(!empty($img_size) && !empty($comment_img))
            {
                $w = $img_size[0];
                $h = $img_size[1];
                $thumbInfo = $this->getThumbInfo($w, $h);
                extract($thumbInfo);
                $thumb_img = empty($thumb_img) ? $comment_img : $comment_img .'?imageMogr2/thumbnail/'.$thumb_img;
            }
            else
            {
                $thumb_size = '0x0';
            }
            $add_time = time();
            $comment = compact('news_id','father_id','uid','comment_content','add_time', 'comment_img','thumb_img','thumb_size');
            $new_comment_id = $this->db->insertRowTable('r_news_comment', $comment);
            if($new_comment_id)
            {
                // 评论楼层
                $this->redis->zadd(REDIS_PREFIX.'NewsComFloor_'.$news_id, $new_comment_id, $new_comment_id);
                $floor = $this->redis->zrank(REDIS_PREFIX.'NewsComFloor_'.$news_id, $new_comment_id)+1;
                $this->base->result['result'] = compact('new_comment_id' ,'floor','comment_img','thumb_img','comment_content', 'thumb_size');
                $this->base->breakCall();
                $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'total_comment', 1);
                $this->db->update("update r_news set total_comment = total_comment+1 where news_id = '{$news_id}'");
                if($this->base->vn >=1400 || ($this->base->vn >= 1200 && $this->base->projectId == 2))
                {
                    $_ENV['client']->userEnergyChange($uid, 'comment',$new_comment_id);
                }
                //回复帖子
                if(isset($postInfo['uid']) && $uid != $postInfo['uid'])
                {
                    $this->base->load('bbs')->addUnReadMsg($postInfo['uid'], array('msgType'=>1, 'sponsor'=>array('uid'=>$uid,'comment_id'=>$new_comment_id), 'quote'=>array('news_id'=>$news_id,'comment_id'=>'0')));
                    //发送IM消息
                }
                //回复评论
                if($father_id > 0 && $uid != $father_uid)
                {
                    $this->base->load('bbs')->addUnReadMsg($father_uid, array('msgType'=>2, 'sponsor'=>array('uid'=>$uid,'comment_id'=>$new_comment_id), 'quote'=>array('news_id'=>$news_id,'comment_id'=>$father_id)));
                    //发送IM消息
                }
                // 更新版块最热列表
                if(isset($postInfo['board']) && !empty($postInfo['board']))
                {
                    foreach ($postInfo['board'] as $board) {
                        $this->redis->ZADD(REDIS_PREFIX.'BoardPostList'.$board['boardId'].'_Hot', time(), $news_id);
                    }
                }
                // 更新标签最热列表
                if(isset($postInfo['tag']) && !empty($postInfo['tag']))
                {
                    foreach ($postInfo['tag'] as $tag) {
                        $this->redis->ZADD(REDIS_PREFIX.'TagPostList'.$tag['tagId'].'_Hot', time(), $news_id);
                    }
                }
            }
            else
            {
                $_ENV['error']->getErrors(100);
                exit;
            }
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }
    /**
     * 检查资讯标题是否重复
     * @return boolen true 为不重复， false 为重复
     */
    public function checkNewsTitle($title, $news_id = 0)
    {
        $title = common::mysql_real_escape_string($title);
        $sql = "select news_id from r_news where title = '{$title}'";
        $news_id > 0 && $sql .= " and news_id != '{$news_id}'";
        $sql .= ' limit 1';
        $result = $this->db->getone($sql);

        return empty($result);
    }
    /**
     * 收藏资讯
     * @param news_id 资讯id
     * @param uid  用户ID
     * @return collection_id  生成的收藏序号
     */
    public function collectNews($news_id, $uid)
    {
        $news_id = $this->db->getone("select news_id from r_news where news_id = {$news_id} and is_show =1");

        if($news_id && $uid)
        {
            if($this->db->getone("select news_id from r_news_collection where news_id = {$news_id} and uid = {$uid} and is_delete = 0"))
            {
                return 1;
            }
            $add_time = time();
            $is_delete = 0;
            $collectArray = compact('news_id','uid','add_time' ,'is_delete');
            $collection_id = $this->db->insertRowTable('r_news_collection', $collectArray);

            $is_success = $collection_id > 0 ? 1 : 0;

            $postInfo = $this->base->load('bbs')->getPostInfo($news_id);
            if(isset($postInfo['uid']) && $uid != $postInfo['uid'])
            {
                $this->base->load('bbs')->addUnReadMsg($postInfo['uid'], array('msgType'=>4, 'sponsor'=>array('uid'=>$uid,'comment_id'=>'0'), 'quote'=>array('news_id'=>$news_id,'comment_id'=>'0')));
            }
            $this->redis->zadd(REDIS_PREFIX.'PostLikeList_'.$news_id, time(), $uid);
            $this->redis->zadd(REDIS_PREFIX.'MyLovePList_'.$uid, $collection_id, $news_id);
            if($this->db->update("update r_news set loves = loves+1 where news_id = '{$news_id}'"))
            {
                $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'loves', 1);
            }
            return 1;
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }
    /**
     * 收藏资讯列表
     * @param uid 用户id
     * @param point 起始收藏id
     * @param direc  用户ID
     * @param offset  数量
     * @param p  页码
     * @return array
     */
    public function getcollectNewsList($uid, $point=0, $direc= 'next', $offset=10, $p =0)
    {
        $result = array();
        if($uid)
        {
            if($p > 0)
            {
                exit();
            }
            else
            {
                $sql = "select record_id as collection_id, news_id from r_news_likes where uid = {$uid} and is_delete = 0 ";
                if($point > 0)
                {
                    $sql .= ' and record_id ';
                    $sql .= $direc == 'next' ? " < {$point} order by record_id DESC" :" > {$point} order by record_id ASC";
                }
                else
                {
                    $sql .= ' order by record_id DESC';
                }
                $sql .= " limit {$offset}";
            }
            $news_ids = $this->db->getAll($sql);
            if($news_ids)
            {
                $result = array();
                foreach($news_ids as $v)
                {
                    $collection = $this->getNewsInfo($v['news_id']);
                    if(empty($collection) || $collection['is_show'] != 1)
                    {
                        $this->db->delDataTable('r_news_likes', "news_id = {$v['news_id']}");
                    }
                    else
                    {
                        unset($collection['content'], $collection['lastupdate'], $collection['is_show'],$collection['is_top'], $collection['a_channel'], $collection['a_start_time'], $collection['a_end_time']);
                        if(isset($collection['thumb_img']))
                        {
                            if(is_array($collection['thumb_img']))
                            {
                                foreach ($collection['thumb_img'] as $key => $thumb_img)
                                {
                                    if(empty($thumb_img))
                                    {
                                        unset($collection['thumb_img'][$key]);
                                    }
                                }
                            }
                        }
                        else
                        {
                            $collection['thumb_img'] = '[]';
                        }
                        $sql = "select count(comment_id) from r_news_comment where news_id = '".$v['news_id']."'";
                        $lightLimt = $this->base->config['NEWS_HOT_COMMENT_LIMIT'];
                        $sql .= " and lights >= {$lightLimt}";
                        $collection['total_lights'] = $this->db->getOne($sql);
                        $result[] = $collection;
                    }
                }
            }
            return $result;
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }
    /**
     * 取消收藏资讯
     * @param news_id 资讯id
     * @param uid  用户ID
     * @return collection_id  生成的收藏序号
     */
    public function cancelcollectNews($news_id, $uid)
    {
        if($news_id && $uid)
        {
            $collection_id = $this->db->getone("select collection_id from r_news_collection where news_id = {$news_id} and uid= {$uid} and is_delete =0");
            if(empty($collection_id))
            {
                return 1;
            }
            $is_delete = 1;
            $result = $this->db->query("update r_news_collection set is_delete = 1 where collection_id = {$collection_id}");
            if($result != false)
            {
                $this->redis->zrem(REDIS_PREFIX.'PostLikeList_'.$news_id, $uid);
                $this->redis->zrem(REDIS_PREFIX.'MyLovePList_'.$uid, $news_id);
                if($this->db->update("update r_news set loves = loves-1 where news_id = '{$news_id}'"))
                {
                    $this->redis->HINCRBY(REDIS_PREFIX. 'NewsInfo_'.$news_id, 'loves', -1);
                }
            }
            return $result ? 1 : 0;
        }
        else
        {
            $_ENV['error']->getErrors(101);
            exit();
        }
    }
    /**
     * 记录客户端打开推送数据
     * @return 
     */
    public function pushWorkRecord($pushData)
    {
        $pushData = json_encode($pushData);
        return $this->redis->sadd(REDIS_PREFIX . 'pushWorkRecord', $pushData) != false;
    }
    /**
     * 统计资讯点击数据
     * @return
     */
    public function makeNewsClickStat($news_id = 0, $from_push = false)
    {
        $news_id = intval($news_id);
        if(empty($news_id)) return ;

        $redisKey = REDIS_PREFIX.'NewsClick'.date("Ymd").'_'.$news_id;
        $this->redis->sadd(REDIS_PREFIX.'NewsClick'.date("Ymd"), $news_id);

        $projectId = $this->base->projectId;
        $client = $this->base->client;
        $statData = $this->redis->hgetall($redisKey);
        if(empty($statData))
        {
            if($projectId == 1)
            {
                $statData['andCount'] = 1;
                $statData['iosCount'] = 0;
                $this->redis->sadd($redisKey.'AndClient', $client);
                if($from_push)
                {
                    $statData['andPushCount'] = 1;
                    $statData['iosPushCount'] = 0;
                    $this->redis->sadd($redisKey.'AndPushClient', $client);
                }
                else
                {
                    $statData['andPushCount'] = $statData['iosPushCount'] = 0;
                }
            }
            else
            {
                $statData['andCount'] = 0;
                $statData['iosCount'] = 1;
                $this->redis->sadd($redisKey.'IosClient', $client);
                if($from_push)
                {
                    $statData['andPushCount'] = 0;
                    $statData['iosPushCount'] = 1;
                    $this->redis->sadd($redisKey.'IosPushClient', $client);
                }
                else
                {
                    $statData['andPushCount'] = $statData['iosPushCount'] = 0;
                }
            }
            $this->redis->hmset($redisKey, $statData);
        }
        else
        {
            $andCount = 0;   // 安卓点击增量
            $andPushCount = 0;   // 安卓推送点击增量
            $iosCount = 0;   // IOS点击增量
            $iosPushCount = 0;   // IOS 推送点击增量
            if($projectId == 1)
            {
                $andCount = 1;
                $this->redis->sadd($redisKey.'AndClient', $client);
                if($from_push)
                {
                    $andPushCount = 1;
                    $this->redis->sadd($redisKey.'AndPushClient', $client);
                }
            }
            else
            {
                $iosCount = 1;
                $this->redis->sadd($redisKey.'IosClient', $client);
                if($from_push)
                {
                    $iosPushCount = 1;
                    $this->redis->sadd($redisKey.'IosPushClient', $client);
                }
            }
            $this->redis->HINCRBY($redisKey, 'andCount', $andCount);
            $this->redis->HINCRBY($redisKey, 'andPushCount', $andPushCount);
            $this->redis->HINCRBY($redisKey, 'iosCount', $iosCount);
            $this->redis->HINCRBY($redisKey, 'iosPushCount', $iosPushCount);
        }
        
        return ;
    }
    /**
     * 保存资讯点击统计数据
     * @return
     */
    public function saveNewsClickData()
    {
        $today = date("Ymd");
        $now = time();
        $redisKey = REDIS_PREFIX.'NewsClick'.$today;

        $newsIds = $this->redis->SMEMBERS($redisKey);
        if($newsIds)
        {
            foreach ($newsIds as $key => $news_id) {
                $statData = $this->redis->hgetall($redisKey.'_'.$news_id);
                if($statData)
                {
                    $statData['news_id'] = $news_id;
                    $statData['add_time'] = $now;
                    $statData['andCCount'] = $this->redis->scard($redisKey.'_'.$news_id.'AndClient');
                    $statData['iosCCount'] = $this->redis->scard($redisKey.'_'.$news_id.'IosClient');
                    $statData['andPushCCount'] = $this->redis->scard($redisKey.'_'.$news_id.'AndPushClient');
                    $statData['iosPushCCount'] = $this->redis->scard($redisKey.'_'.$news_id.'IosPushClient');
                    $this->db->insertRowTable('r_news_click', $statData);
                }
                $this->redis->del($redisKey.'_'.$news_id);
                $this->redis->del($redisKey.'_'.$news_id.'AndClient');
                $this->redis->del($redisKey.'_'.$news_id.'IosClient');
                $this->redis->del($redisKey.'_'.$news_id.'AndPushClient');
                $this->redis->del($redisKey.'_'.$news_id.'IosPushClient');
            }
        }
        $this->redis->del($redisKey);
        return ;
    }
    /**
     * 定时任务， 显示有道文章
     * @return
     */
    public function timerShowNews()
    {
        $newsIds = $this->redis->SMEMBERS(REDIS_PREFIX. 'NewsShowTimers');
        if(empty($newsIds)) return ;
        foreach ($newsIds as $news_id) {
            $newsinfo = $this->base->load('bbs')->getPostInfo($news_id);
            if(empty($newsinfo)) continue;
            if($newsinfo['start_time'] > time()) continue;
            extract($newsinfo);
            $postId = $news_id;
            if($this->db->updateRowTable('r_news', array('news_id' => $postId, 'is_show'=> 1)))
            {
                $this->redis->SREM(REDIS_PREFIX. 'NewsShowTimers', $postId);
                $this->redis->hset(REDIS_PREFIX.'NewsInfo_'.$postId, 'is_show',1);
                $is_yd = stripos($this->redis->hget(REDIS_PREFIX.'NewsInfo_'.$postId, 'board'), '0') != false ? 1 : 0;
                if(!empty($a_channel))
                {
                    if($is_yd == 1)
                    {
                        $this->redis->HSET(REDIS_PREFIX.'ActivityNews', $a_channel, $postId);
                    }
                    else{
                        foreach ($board as $v) {
                            if(!empty($v['boardId']))
                            {
                                $this->redis->ZADD(REDIS_PREFIX.'ACT_'.$a_channel.'_'.$v['boardId'], $a_start_time, $postId);
                            }
                        }
                        foreach ($tag as $v['tagId']) {
                            $this->redis->ZADD(REDIS_PREFIX.'ACT_'.$a_channel.'_'.$v['tagId'], $a_start_time, $postId);
                        }
                    }
                }
                else
                {
                    $lastCT = $this->db->getOne("select add_time from r_news_comment where news_id = '{$postId}' and is_show = 1 order by news_id DESC limit 1");
                    $lastCT = intval($lastCT);
                    $is_yd == 1 && $this->redis->ZADD(REDIS_PREFIX . 'NewsList', $add_time, $postId);
                    foreach ($board as $v) {
                        if(!empty($v['boardId']))
                        {
                            $this->db->updateRowTable('r_boardPost', array('boardId' => $v['boardId'],'news_id' => $postId,'isOn' => 1));
                            $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v['boardId'].'_New', $add_time, $postId);
                            $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v['boardId'].'_Hot', 0, $postId);
                        }
                    }
                    foreach ($tag as $v) {
                        $this->db->updateRowTable('r_tagPost', array('tagId' => $v['tagId'], 'news_id' => $postId,'isOn' => 1));
                        $this->redis->zadd(REDIS_PREFIX.'TagPostList'.$v['tagId'].'_New', $add_time, $postId);
                        $this->redis->zadd(REDIS_PREFIX.'TagPostList'.$v['tagId'].'_Hot', $lastCT, $postId);
                    }
                }
            }
        }
        return ;
    }
    /**
     * 替换评论中的@用户
     * @return
    */
    public function replaceComment($content)
    {
        $content = trim($content);
        if($this->base->vn < 1700 || ($this->base->vn < 1900 && $this->base->projectId == 1))
        {
            preg_match_all('/(<at href="joggers:\/\/profile\/\d+">.*<\/at>)/U', $content, $matches);
            if(!empty($matches[1]))
            {
                foreach ($matches[1] as $str) {
                    $content = preg_replace('/<at href="joggers:\/\/profile\/\d+">(.*)<\/at>/U', '@${1} ', $content);
                }
            }
        }
        return $content;
    }
    /**
     * 生成缩略图尺寸
     * @return
    */
    public function getThumbInfo($width, $height)
    {
        $width = intval($width);
        $height = intval($height);
        $ratio = round($height/$width, 2);
        $r = round(340/200, 2);
        $rd = round(200/340, 2);
        $thumb_img = '';
        if($width > 200 && $height > 340 && $ratio > $r)
        {
            $thumb_img = '200x';
            $width = 200;
            $height = intval(200*$ratio);
        }
        else if($width > 340 && $height > 340 && $ratio > $rd && $ratio < $r)
        {
            $thumb_img = '340x340>';
            if($ratio < 1)
            {
                $width = 340;
                $height = intval(340*$ratio);
            }
            else
            {
                $width = intval(340/$ratio);
                $height = 340;
            }
        }
        else if($width > 340 && $height > 200 && $ratio < $rd)
        {
            $thumb_img = 'x200';
            $width = intval(200/$ratio);
            $height = 200;
        }
        $thumb_size = $width.'x'.$height;
        return compact('thumb_img', 'thumb_size');
    }


    /**
     * 获取评论内容 根据帖子ID和评论ID
     * @param  [type] $newsId    [description]
     * @param  [type] $commentId [description]
     * @return [type]            [description]
     */
    public function getNewsComment($commentId){
        $comment_content = $this->db->getOne("select comment_content from r_news_comment where comment_id= {$commentId}");
        return  $comment_content ? $comment_content : "";
    }
}
?>
